import config  from "../config/app.js"

export const request = (options) => {
	return new Promise((resolve, reject) => {
		let token = uni.getStorageSync('Authorization')
		// 在登录的时候需要储存 token uni.setStorageSync("Authorization","这里是登录获取的token值")
		uni.request({
			url: config.BASE_URL + options.url,
			data: options.data || {},
			method: options.method || 'GET',
			header: options.header || {
				// 通过 Authorization 存放 token 值
				Authorization: token,
			},
			responseType: options.responseType || "application/json;charset=utf-8",
			success: (res) => {
				resolve(res.data)
			},
			fail: (err) => {
				// 页面中弹框显示失败
				uni.showToast({
					title: '接口请求失败',
					icon: "none"
				})
				// 返回错误消息
				reject(err)
			},
			catch: (e) => {
				console.log(e);
			}
		})
	})
}

export function fileUploadImage(url) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
		  url: config.BASE_URL + "/upload",     // 后端api接口
		  filePath: url, // uni.chooseImage函数调用后获取的本地文件路径
		  name:'file',     //后端通过'file'获取上传的文件对象
		  formData: {},
			fileType: "image",
		  header:{
				// "Content-Type": "multipart/form-data",
				"Authorization": uni.getStorageSync('Authorization'),
			},
			success: (res) => {
				resolve(res.data)
			},
			fail: (err) => {
				// 页面中弹框显示失败
				uni.showToast({
					title: '接口请求失败',
					icon: "none"
				})
				// 返回错误消息
				reject(err)
			},
		});
	})
}

export function uploadCurrentImage(imgList) {
	if (imgList.length <= 0) {
		uni.showToast({
			title: '需要上传房源图片',
			icon: "none"
		})
		return;
	}
	let promiseList = []
	for (let i=0; i<imgList.length; i++) {
		promiseList.push(fileUploadImage(imgList[i]));
	}
	return new Promise((resolve, reject) => {
	  Promise.all(promiseList).then((res) => {
	  	let result = []
	  	for (let j=0; j<res.length; j++) {
	  		let jsonResult = JSON.parse(res[j]);
	  		result.push(jsonResult.data.urls[0].url);
	  	}
	  	resolve(result);
	  }).catch((error) => {
	    console.log(error)      // 失败了，打出 '失败'
	  })
	});
	
}

// 将对象导出外部引入使用
export default {
	request,
	fileUploadImage,
	uploadCurrentImage
}